﻿using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace GemTowerDefence
{
  public class WaveManager
  {
    private readonly Queue<Wave> _waves; // A queue of all our waves
    private readonly Player _player;
    private readonly int _numberOfWaves; // How many waves the game will have

    public WaveManager(Player player, TileMap tileMap, int numberOfWaves,
                       Texture2D enemyTexture, Texture2D healthTexture)
    {
      _waves = new Queue<Wave>();
      _player = player;
      _numberOfWaves = numberOfWaves;

      for (int i = 0; i < numberOfWaves; i++)
      {
        const int initialNumerOfEnemies = 15;

        var wave = new Wave(i, initialNumerOfEnemies, player, tileMap, enemyTexture, healthTexture);

        _waves.Enqueue(wave);
      }
      State = WavesState.Initial;
    }

    public int NumberOfWaves
    {
      get { return _numberOfWaves; }
    }

    public Wave CurrentWave // Get the wave at the front of the queue
    {
      get { return _waves.Peek(); }
    }

    public List<Enemy> Enemies // Get a list of the current enemeies
    {
      get { return CurrentWave.Enemies; }
    }

    public int Round // Returns the wave number
    {
      get { return CurrentWave.RoundNumber; }
    }

    public int AvailableGems
    {
      get { return _player.AvailableGems; }
      set { _player.AvailableGems = value; }
    }

    public bool IsUpdatingPath { get; set; }

    public WavesState State { get; private set; }

    public void Update(GameTime gameTime)
    {
      CurrentWave.Update(gameTime); // Update the wave

      if (IsUpdatingPath)
      {
        State = WavesState.UpdatingPath;
      }
      if (CurrentWave.RoundOver && State == WavesState.Running)
      {
        AvailableGems = _player.InitialGems;
        State = WavesState.PickingGems;
      }
      else if (AvailableGems == 0 && (State == WavesState.PickingGems || State == WavesState.Initial))
      {
        State = WavesState.PickedGems;
      }
      else if (!IsUpdatingPath && State == WavesState.UpdatingPath && AvailableGems > 0)
      {
        State = WavesState.PickingGems;
      }
      else if (!IsUpdatingPath && State == WavesState.UpdatingPath && !_player.IsAddingTower)
      {
        State = WavesState.UpdatedPath;
        if (_waves.Count > 0)
        {
          _waves.Dequeue(); // Remove the finished wave
          _waves.Peek().Start(); // Start the next one
        }
      }
      else if (CurrentWave.IsStarted && State == WavesState.UpdatedPath)
      {
        State = WavesState.Running;
      }

    }

    public void Draw(SpriteBatch spriteBatch)
    {
      CurrentWave.Draw(spriteBatch);
    }

  }

  public enum WavesState
  {
    Initial,
    PickingGems,
    PickedGems,
    UpdatingPath,
    UpdatedPath,
    Running
  }

}